﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;

namespace MvcSinglRDemo.Models
{
    [HubName("SystemHub")]
    public class SystemHub : Hub
    {
        public static List<UserInfo> ConnectedUsers = new List<UserInfo>();


        public void Connect(string userID, string userName, string deptName)
        {

            var id = Context.ConnectionId;

            if (ConnectedUsers.Count(x=>x.ConnectionId==id)==0)
            {
                if (ConnectedUsers.Count(x => x.UserID == userID) > 0)
                {
                    var items = ConnectedUsers.Where(d => d.UserID == userID).ToList();
                    foreach (var item in items)
                    {
                        Clients.AllExcept(id).onUserDisconnected(item.ConnectionId,item.UserName);
                    }
                    ConnectedUsers.RemoveAll(x => x.UserID == userID);
                }

                ConnectedUsers.Add(new UserInfo { ConnectionId = id, UserID = userID, UserName = userName, DeptName = deptName, LoginTime = DateTime.Now });
                Clients.Caller.onConnected(id, userName, ConnectedUsers);
                Clients.AllExcept(id).onNewUserConnected(id, userID, userName, deptName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            }
        }

        public void SendPrivateMessage(string toUserId, string message)
        {

            string fromUserId = Context.ConnectionId;
            var toUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == toUserId);
            var fromUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == fromUserId);
            if (toUser!=null && fromUser!=null)
            {
                Clients.Client(toUserId).receivePrivateMessage(fromUserId, fromUser.UserName, message);

            }
            else
            {
                Clients.Caller.absentSubscriber();
            }
        }

        public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled)
        {
            var item = ConnectedUsers.FirstOrDefault(x=>x.ConnectionId==Context.ConnectionId);
            if(item!=null){

                Clients.All.onUserDisconnected(item.ConnectionId, item.UserName);
                ConnectedUsers.Remove(item);
            }


            return base.OnDisconnected(stopCalled);
        }
    }
}